import type { IGetWorkTemplateListProps } from '@/request/types/workType'
import useTemplateStore from '@/store/modules/templateStore'
import { ref, onUnmounted } from 'vue'
type actionType = 'templateList' | 'myWorkList'
const useLoadMore = (action: actionType, params: IGetWorkTemplateListProps) => {
  const templateStore = useTemplateStore()
  const loadPageIndex = ref(params.pageIndex)
  const loadPageSize = ref(params.pageSize)
  //判断是否加载到底
  const isLoadMore = ref(false)

  const loadMore = async (
    loadMoreParams: Partial<IGetWorkTemplateListProps> = {}
  ) => {
    switch (action) {
      case 'templateList': {
        await templateStore.setTemplateList({
          ...params,
          pageIndex: loadPageIndex.value,
          pageSize: loadPageSize.value,
          ...loadMoreParams,
        })
        isLoadMore.value =
          templateStore.templatesList.length < templateStore.templateTotal
        break
      }
      case 'myWorkList': {
        await templateStore.setMyWorkTemplate({
          ...params,
          pageIndex: loadPageIndex.value,
          pageSize: loadPageSize.value,
          ...loadMoreParams,
        })
        isLoadMore.value =
          templateStore.myWorkTemplate.length <
          templateStore.myWorkTemplateTotal
        break
      }
    }
    loadPageIndex.value++
  }
  const setPageIndex = (page: number, pageSize: number) => {
    if (page > 0) {
      loadPageIndex.value = page - 1
    }
    pageSize && (loadPageSize.value = pageSize)
  }
  onUnmounted(() => {
    templateStore.resetTemplateList()
    loadPageIndex.value = 0
    loadPageSize.value = 8
    templateStore.resetMyWorkTemplate()
  })
  return {
    isLoadMore,
    loadMore,
    setPageIndex,
  }
}

export default useLoadMore
